package com.easyselection.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easyselection.dto.Result;
import com.easyselection.entity.Shop;
import com.easyselection.mapper.ShopMapper;
import com.easyselection.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easyselection.utils.CacheClient;
import com.easyselection.utils.RedisConstants;
import com.easyselection.utils.RedisData;
import com.easyselection.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {

        // 缓存空值解决缓存穿透问题
        // Shop shop = queryWithPassThrough(id);
        //工具类实现
       // Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
        //        this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);


        // 利用互斥锁解决缓存击穿问题
//        Shop shop = queryWithMutex(id);


        // 基于逻辑过期方案解决缓存击穿问题
        // Shop shop = queryWithLogicalExpire(id);
        //工具类实现
        Shop shop = cacheClient.queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY, RedisConstants.LOCK_SHOP_KEY,
                id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);
        return shop == null ? Result.fail("店铺不存在!") : Result.ok(shop);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 基于逻辑过期方案解决缓存击穿问题
     * @param id
     * @return
     */
    private Shop queryWithLogicalExpire(Long id){
        //1.从redis当中查询商铺缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isBlank(shopJson)) {
            //3.未命中返回空
            return null;
        }

        //4.判断缓存是否过期
        //反序列化 将Json数据转换为redisData对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        //将data Json字符串也反序列化为shop对象
        JSONObject JsonObject = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(JsonObject, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5. 判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            //5.1 未过期返回商铺信息
            return shop;
        }

        //5.2 已过期 需要进行缓存重建
        //6. 缓存重建
        //6.1 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6.2 获取锁成功 开启独立线程
        if(isLock){

            //双重检验锁机制: 再次检查缓存是否过期（防止多个线程同时重建缓存）
            String currentShopJson = stringRedisTemplate.opsForValue().get(key);
            //反序列化
            RedisData currentRedisData = JSONUtil.toBean(currentShopJson, RedisData.class);
            if (currentRedisData.getExpireTime().isAfter(LocalDateTime.now())) {
                unLock(lockKey);
                return JSONUtil.toBean((JSONObject) currentRedisData.getData(), Shop.class);
            }

            // 提交独立线程进行缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    saveShopToRedis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }


        //6.3 返回旧的缓存信息
        return shop;
    }
    

    //在利用逻辑过期解决缓存击穿问题之前, 进行缓存预热
    /**
     *
     * @param id 表的主键id
     * @param expireSeconds 加上逻辑过期时间, 20秒
     */
    public void saveShopToRedis(Long id, Long expireSeconds) throws InterruptedException {
        //1.查询商铺数据
        Shop shop = getById(id);
        //模拟重建缓存的延迟
        Thread.sleep(200);
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存重建需要做 双重检测锁定（Double Check Lock）:
     * 第一次检测: 在获取锁之前，检查缓存是否存在。如果缓存存在，直接返回结果。
     * 第二次检测: 在获取锁之后，再次检查缓存是否存在。如果缓存已经存在，直接返回结果。
     * 这一步是为了防止在等待锁的过程中，其他线程已经重建了缓存。
     * @param id
     * @return
     */
    private Shop queryWithMutex(Long id) {
        //1.从redis当中查询商铺缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
            //3.存在, 返回信息
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断命中的是否是空字符串, 如果是则返回空信息
        if(shopJson != null){
            return null;
        }
        //4.1 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            //4.2 判断是否获取成功
            boolean isLock = tryLock(lockKey);
            if(!isLock){
                //4.3 失败, 休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            // 第二次检测：再次检查缓存是否存在（防止多个线程同时重建缓存）
            shopJson = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(shopJson)) {
                return JSONUtil.toBean(shopJson, Shop.class);
            }

            //4.4 成功,缓存重建  根据id查询数据库
            shop = getById(id);
            //模拟缓存重建的延时
            Thread.sleep(200);

            //5. 为了解决缓存穿透, 将空值写入redis, 并返回错误信息
            if(shop == null) {
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                //返回错误信息
                return null;
            }
            //6. 存在 将shop对象写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e){
            throw new RuntimeException(e);
        } finally {
            //7.释放互斥锁
            unLock(lockKey);
        }
        //8. 返回信息
        return shop;
    }


    //缓存空值解决缓存穿透问题
    private Shop queryWithPassThrough(Long id){
        //1.从redis当中查询商铺缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
            //3.存在, 返回信息
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断命中的是否是空字符串, 如果是则返回空信息
        if(shopJson != null){
            return null;
        }

        //4.不存在 根据id查询数据库
        Shop shop = getById(id);
        //5.数据库中不存在, 为了解决缓存穿透, 将空值写入redis, 并返回错误信息
        if(shop == null) {
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误信息
            return null;
        }
        //6、存在 写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //返回信息
        return shop;
    }

    /**
     * 获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key){
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, "1",
                RedisConstants.LOCK_SHOP_TTL, TimeUnit.MINUTES));
    }

    /**
     * 释放锁
     * @param key
     */
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        if(shop.getId() == null) return Result.fail("店铺id不能为空!");
        //1.更新数据库
        updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete( RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    /**
     * 根据商铺类型分页查询商铺信息
     * @param typeId 商铺类型
     * @param current 页码
     * @return 商铺列表
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1. 是否需要根据坐标查询
        if(x == null || y == null){
            // 按照数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        //2. 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        //3. 查询redis, 按照距离排序、分页。结果：shopId distance
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        // Geosearch key  fromLonLat x, y byradius m withdistance
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key, GeoReference.fromCoordinate(x, y)
                , new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        //4. 解析出id
        if(results == null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }

        // 4.1 截取from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>();
        list.stream().skip(from).forEach(result->{
            //4.2 获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            //4.3 获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("order by field(id, " + idStr + ")").list();
        // 6. 将距离写入shop
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
}
